import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../../../common/utils/toast_util.dart';
import '../../../common/routers/names.dart'; // 导入路由名称

import 'index.dart';

class PostEventPage extends GetView<PostEventController> {
  const PostEventPage({super.key});

  // 主视图
  Widget _buildView() {
    
    return GestureDetector(
      // 点击页面其他地方时清除所有输入框焦点并收起键盘
      onTap: () {
        controller.clearAllFocus();
      },
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
          // 标题
          _buildListItem(
            label: '标题',
            placeholder: '请输入活动的标题',
            controller: controller.titleController,
            focusNode: controller.titleFocusNode,
            isInput: true,
          ),
          
          // 地点（增强版：支持实时定位）
          _buildLocationSection(),
          
          // 开始时间
          Obx(() => _buildListItem(
            label: '开始时间',
            value: controller.startDateText.value.isEmpty ? '' : controller.startDateText.value,
            placeholder: '请选择开始时间',
            onTap: () {
              controller.openDateTimePicker(Get.context!, true);
            },
            icon: Icons.chevron_right,
          )),
          
          // 结束时间
          Obx(() => _buildListItem(
            label: '结束时间',
            value: controller.endDateText.value.isEmpty ? '' : controller.endDateText.value,
            placeholder: '请选择结束时间',
            onTap: () {
              // 如果是结束时间，检查是否已选择开始时间
              if (controller.startDateText.value.isEmpty) {
                ToastUtil.warning('请先选择开始时间');
                return;
              }
              controller.openDateTimePicker(Get.context!, false);
            },
            icon: Icons.chevron_right,
          )),
          
          // 🕒 时间范围和持续时间显示
          Obx(() {
            if (controller.startDateText.value.isNotEmpty && 
                controller.endDateText.value.isNotEmpty) {
              return Container(
                margin: const EdgeInsets.symmetric(vertical: 8),
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: const Color(0xFFF8F9FA),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: const Color(0xFFE9ECEF)),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        const Icon(Icons.schedule, size: 16, color: Color(0xFF6C757D)),
                        const SizedBox(width: 4),
                        const Text(
                          '活动时间',
                          style: TextStyle(
                            fontSize: 13,
                            color: Color(0xFF6C757D),
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '${controller.startDateText.value} 至 ${controller.endDateText.value}',
                      style: const TextStyle(
                        fontSize: 14,
                        color: Color(0xFF495057),
                        height: 1.4,
                      ),
                    ),
                    if (controller.startDate.value != null && controller.endDate.value != null) ...[
                      const SizedBox(height: 4),
                      Text(
                        '持续时间：${_calculateDisplayDuration()}',
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xFF28A745),
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ],
                ),
              );
            }
            return const SizedBox.shrink();
          }),
          
          // 限制
          Obx(() => _buildListItem(
            label: '限制',
            value: controller.selectedLimit.value,
            onTap: () => controller.openLimitPicker(Get.context!),
            icon: Icons.chevron_right,
          )),
          
          // 人数
          _buildListItem(
            label: '人数',
            placeholder: '请输入参与人数',
            controller: controller.peopleCountController,
            focusNode: controller.peopleCountFocusNode,
            isInput: true,
            isNumberInput: true, // 标记为数字输入
          ),
          
          // 消费
          Obx(() => _buildListItem(
            label: '消费',
            value: controller.selectedPayment.value,
            onTap: () => controller.openPaymentPicker(Get.context!),
            icon: Icons.chevron_right,
          )),
          
          const SizedBox(height: 24),
          
          // 活动详情
          _buildEventDetailsArea(),
          
          const SizedBox(height: 24),
          
          // 活动封面展示
          _buildImageUploadSection(),
          
          const SizedBox(height: 32),
          
          // 发布按钮
          _buildPublishButton(),
          
          const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }
  
  // 🗺️ 地点选择区域（学习首页实现）
  Widget _buildLocationSection() {
    return Column(
      children: [
        GestureDetector(
          onTap: () async {
            // 清除所有输入框焦点并收起键盘
            controller.clearAllFocus();
            await Future.delayed(const Duration(milliseconds: 150));
            
            // 🎯 跳转到地图页面并等待用户选择位置（学习首页实现）
            final result = await Get.toNamed(RouteNames.systemMap);
            
            // 🎯 如果用户选择了位置，更新发布页面位置信息
            if (result != null && result is Map<String, dynamic>) {
              controller.updateLocationFromMap(result);
            }
          },
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 16),
            child: Row(
              children: [
                // 左侧标题
                const SizedBox(
                  width: 80,
                  child: Text(
                    '地点',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  ),
                ),
                // 中间内容区域（动态位置显示）
                Expanded(
                  child: Obx(() => Row(
                    children: [
                      // 定位图标（加载时显示动画）
                      controller.isLocationLoading.value
                          ? const SizedBox(
                              width: 16,
                              height: 16,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
                              ),
                            )
                          : Icon(
                              Icons.location_on,
                              size: 16,
                              color: controller.isDefaultLocation.value 
                                  ? Colors.grey[500] 
                                  : const Color(0xFFE33641),
                            ),
                      const SizedBox(width: 6),
                      // 位置信息文本
                      Expanded(
                        child: Text(
                          controller.location.value,
                          textAlign: TextAlign.left,
                          style: TextStyle(
                            fontSize: 16,
                            color: controller.isLocationLoading.value
                                ? Colors.grey[500]
                                : (controller.isDefaultLocation.value
                                    ? Colors.grey[500]
                                    : Colors.black87),
                          ),
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                      ),
                    ],
                  )),
                ),
                // 右侧按钮组
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 刷新定位按钮
                    GestureDetector(
                      onTap: controller.isLocationLoading.value ? null : controller.refreshLocation,
                      child: Container(
                        padding: const EdgeInsets.all(6),
                        child: Icon(
                          Icons.refresh,
                          size: 18,
                          color: controller.isLocationLoading.value 
                              ? Colors.grey[400] 
                              : const Color(0xFFE33641),
                        ),
                      ),
                    ),
                    const SizedBox(width: 4),
                    // 跳转箭头
                    Icon(
                      Icons.chevron_right,
                      color: Colors.grey[400],
                      size: 20,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        // 底部分隔线
        Container(
          height: 1,
          color: Colors.grey[200],
        ),
        // 位置状态提示（可选）
        Obx(() => controller.isDefaultLocation.value
            ? Container(
                padding: const EdgeInsets.symmetric(horizontal: 80, vertical: 8),
                child: Row(
                  children: [
                    Icon(Icons.info_outline, size: 14, color: Colors.orange[600]),
                    const SizedBox(width: 4),
                    Expanded(
                      child: Text(
                        '正在使用默认位置，点击获取当前位置或选择其他位置',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.orange[600],
                        ),
                      ),
                    ),
                  ],
                ),
              )
            : const SizedBox.shrink()),
      ],
    );
  }

  // 三段式列表项通用组件
  Widget _buildListItem({
    required String label,
    String? value,
    String? placeholder,
    TextEditingController? controller,
    FocusNode? focusNode,
    VoidCallback? onTap,
    IconData? icon,
    bool isInput = false,
    bool isNumberInput = false, // 新增：是否为数字输入
  }) {
    return Column(
      children: [
        GestureDetector(
          onTap: onTap,
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 16),
            child: Row(
              children: [
                // 左侧标题
                SizedBox(
                  width: 80,
                  child: Text(
                    label,
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.black87,
                    ),
                  ),
                ),
                // 中间内容区域
                Expanded(
                  child: isInput
                      ? SizedBox(
                          height: 20, // 固定高度，与Text保持一致
                          child: TextField(
                            controller: controller,
                            focusNode: focusNode,
                            textAlign: TextAlign.right,
                            textInputAction: TextInputAction.done, // 显示完成按钮
                            keyboardType: isNumberInput ? TextInputType.number : TextInputType.text,
                            inputFormatters: isNumberInput ? [
                              FilteringTextInputFormatter.digitsOnly, // 只允许数字
                              LengthLimitingTextInputFormatter(3), // 限制最多3位数（999人）
                            ] : null,
                            onSubmitted: (value) {
                              // 提交时收起键盘
                              if (focusNode != null) {
                                focusNode.unfocus();
                              }
                            },
                            decoration: InputDecoration(
                              hintText: placeholder,
                              hintStyle: TextStyle(
                                color: Colors.grey[400],
                                fontSize: 16,
                              ),
                              border: InputBorder.none,
                              contentPadding: EdgeInsets.zero,
                              isDense: true, // 紧凑模式
                            ),
                            style: const TextStyle(
                              fontSize: 16,
                              color: Colors.black87,
                            ),
                          ),
                        )
                      : Text(
                          value?.isNotEmpty == true ? value! : (placeholder ?? ''),
                          textAlign: TextAlign.right,
                          style: TextStyle(
                            fontSize: 16,
                            color: value?.isNotEmpty == true 
                                ? Colors.black87 
                                : Colors.grey[400],
                          ),
                        ),
                ),
                // 右侧图标
                if (icon != null) ...[
                  const SizedBox(width: 8),
                  Icon(
                    icon,
                    color: Colors.grey[400],
                    size: 20,
                  ),
                ],
              ],
            ),
          ),
        ),
        // 底部分隔线
        Container(
          height: 1,
          color: Colors.grey[200],
        ),
      ],
    );
  }
  
  // 图片上传区域
  Widget _buildImageUploadSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        GestureDetector(
          onTap: () {
            // 点击活动封面标题时也清除焦点
            controller.clearAllFocus();
          },
          child: Row(
            children: [
              const Text(
                '活动封面展示',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.black87,
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(width: 8),
              // 📊 显示图片数量限制提示
              Obx(() {
                // 🎯 使用图片列表计数（支持多张图片）
                final imageCount = controller.activityImages.length;
                return Text(
                  '($imageCount/4)',
                  style: TextStyle(
                    fontSize: 12,
                    color: imageCount >= 4 ? const Color(0xFFE33641) : Colors.grey[500],
                    fontWeight: FontWeight.w400,
                  ),
                );
              }),
            ],
          ),
        ),
        const SizedBox(height: 12),
        // 🖼️ 多张图片上传区域（最多4张图片）
        Obx(() {
          // 🎯 使用图片列表（支持多张图片，学习发布评论实现）
          final imageList = controller.activityImages;
          final isUploading = controller.isUploadingActivityImage.value;
          
          return Wrap(
            spacing: 8,
            runSpacing: 8,
            children: [
              // 📸 显示已选择的图片
              ...imageList.asMap().entries.map((entry) {
                final imagePath = entry.value;
                
                return Stack(
                  children: [
                    Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(
                          color: Colors.grey[300]!,
                          width: 1,
                        ),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: imagePath.startsWith('http')
                            ? Image.network(
                                imagePath,
                                fit: BoxFit.cover,
                                loadingBuilder: (context, child, loadingProgress) {
                                  if (loadingProgress == null) return child;
                                  return Container(
                                    color: Colors.grey[100],
                                    child: Center(
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2,
                                        value: loadingProgress.expectedTotalBytes != null
                                            ? loadingProgress.cumulativeBytesLoaded /
                                                loadingProgress.expectedTotalBytes!
                                            : null,
                                        valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
                                      ),
                                    ),
                                  );
                                },
                                errorBuilder: (context, error, stackTrace) {
                                  return Container(
                                    color: Colors.grey[100],
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Icon(Icons.image_not_supported, size: 20, color: Colors.grey[400]),
                                        Text(
                                          '加载失败',
                                          style: TextStyle(fontSize: 8, color: Colors.grey[500]),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                              )
                            : Image.file(
                                File(imagePath),
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) {
                                  return Container(
                                    color: Colors.grey[100],
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Icon(Icons.image_not_supported, size: 20, color: Colors.grey[400]),
                                        Text(
                                          '图片错误',
                                          style: TextStyle(fontSize: 8, color: Colors.grey[500]),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                              ),
                      ),
                    ),
                    // ❌ 删除按钮
                    Positioned(
                      top: -2,
                      right: -2,
                      child: GestureDetector(
                        onTap: () {
                          controller.clearAllFocus();
                          // 🎯 使用图片列表删除逻辑（支持多张图片）
                          controller.removeActivityImage(entry.key);
                        },
                        child: Container(
                          width: 20,
                          height: 20,
                          decoration: BoxDecoration(
                            color: Colors.red,
                            shape: BoxShape.circle,
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(0.2),
                                blurRadius: 2,
                                offset: Offset(0, 1),
                              ),
                            ],
                          ),
                          child: Icon(
                            Icons.close,
                            size: 12,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ],
                );
              }).toList(),
              
              // ➕ 添加图片按钮（最多4张图片限制）
              if (imageList.length < 4) // ✅ 限制最多4张图片
                GestureDetector(
                  onTap: () => controller.pickActivityImage(),
                  child: Container(
                    width: 80,
                    height: 80,
                    decoration: BoxDecoration(
                      color: Colors.grey[200],
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: Colors.grey[300]!,
                        width: 1,
                      ),
                    ),
                    child: isUploading
                        ? Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                width: 20,
                                height: 20,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
                                ),
                              ),
                              SizedBox(height: 4),
                              Text(
                                '上传中...',
                                style: TextStyle(
                                  fontSize: 8,
                                  color: Colors.grey[600],
                                ),
                              ),
                            ],
                          )
                        : Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                imageList.isEmpty ? Icons.add : Icons.add_photo_alternate,
                                size: 24,
                                color: Colors.grey[400],
                              ),
                              if (imageList.isEmpty)
                                Padding(
                                  padding: EdgeInsets.only(top: 4),
                                  child: Text(
                                    '添加图片',
                                    style: TextStyle(
                                      fontSize: 8,
                                      color: Colors.grey[500],
                                    ),
                                  ),
                                ),
                            ],
                          ),
                  ),
                ),
            ],
          );
        }),
      ],
    );
  }
  
  // 发布按钮
  Widget _buildPublishButton() {
    return SizedBox(
      width: double.infinity,
      height: 48,
      child: Obx(() => ElevatedButton(
        onPressed: controller.isLoading.value ? null : controller.submitForm,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFFE33641),
          disabledBackgroundColor: Colors.grey[400],
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(24),
          ),
          elevation: 0,
        ),
        child: controller.isLoading.value
            ? Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  ),
                  const SizedBox(width: 8),
                  const Text(
                    '发布中...',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      color: Colors.white,
                    ),
                  ),
                ],
              )
            : const Text(
                '发布',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: Colors.white,
                ),
              ),
      )),
    );
  }
  

  
  // 🕒 计算并格式化显示持续时间
  String _calculateDisplayDuration() {
    if (controller.startDate.value == null || controller.endDate.value == null) {
      return '未知';
    }
    
    final duration = controller.endDate.value!.difference(controller.startDate.value!);
    final totalMinutes = duration.inMinutes;
    
    if (totalMinutes < 60) {
      return '${totalMinutes}分钟';
    } else if (totalMinutes < 1440) { // 24小时
      final hours = totalMinutes ~/ 60;
      final minutes = totalMinutes % 60;
      if (minutes == 0) {
        return '${hours}小时';
      } else {
        return '${hours}小时${minutes}分钟';
      }
    } else {
      final days = totalMinutes ~/ 1440;
      final remainingHours = (totalMinutes % 1440) ~/ 60;
      if (remainingHours == 0) {
        return '${days}天';
      } else {
        return '${days}天${remainingHours}小时';
      }
    }
  }

  // 活动详情文本区域
  Widget _buildEventDetailsArea() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        GestureDetector(
          onTap: () {
            // 点击活动详情标题时也清除焦点
            controller.clearAllFocus();
          },
          child: Text(
            "活动详情",
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
          ),
        ),
        const SizedBox(height: 8),
        Container(
          decoration: BoxDecoration(
            color: Colors.grey[200],
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: TextField(
            controller: controller.detailsController,
            focusNode: controller.detailsFocusNode,
            maxLines: 5,
            maxLength: 150,
            textInputAction: TextInputAction.done, // 显示完成按钮
            onSubmitted: (value) {
              // 提交时收起键盘
              controller.detailsFocusNode.unfocus();
            },
            decoration: InputDecoration(
              hintText: "请输入活动详情",
              hintStyle: TextStyle(color: Colors.grey[500]),
              border: InputBorder.none,
              counterText: "",
            ),
            onChanged: controller.updateDetailsLength,
          ),
        ),
        Align(
          alignment: Alignment.centerRight,
          child: Obx(() => Text(
            "${controller.detailsLength.value}/150",
            style: TextStyle(color: Colors.grey),
          )),
        ),
        const SizedBox(height: 10),
      ],
    );
  }
  


  @override
  Widget build(BuildContext context) {
    return GetBuilder<PostEventController>(
      init: PostEventController(),
      id: "post_event",
      builder: (_) {
        return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            leading: IconButton(
              icon: const Icon(
                Icons.arrow_back_ios,
                color: Colors.black87,
                size: 20,
              ),
              onPressed: () => Get.back(),
            ),
            title: const Text(
              '发布活动',
              style: TextStyle(
                color: Colors.black87,
                fontSize: 18,
                fontWeight: FontWeight.w500,
              ),
            ),
            centerTitle: true,
          ),
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }
}
